package bank.driver.sockets;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import bank.server.sockets.*;

public class SocketMessenger {

	private String host;
	private int port;
	private Socket sock;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	
	public SocketMessenger(String host, int port) {
		this.host = host;
		this.port = port;
	}
	
	private void connect() throws IOException{
		if (this.sock == null || this.sock.isClosed()){
			this.sock = new Socket(this.host, this.port, null, 0);
			this.out = new ObjectOutputStream(this.sock.getOutputStream());
			this.in = new ObjectInputStream(this.sock.getInputStream());
		}
	}
	
	public synchronized Response send(Request request) throws UnknownHostException,
	                                                          IOException {
		this.connect();
		out.writeObject(request);
		out.flush();
		try {
			return (Response)in.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new IOException("No Response");
		}
	}
}
